<template>
  <div class="nw-auth-page">
    <div class="auth-container">
      <div class="page-login--form">
        <el-card :body-style="{ padding: '30px 20px 40px' }">
          <div class="form-header text-center">EStar</div>
          <el-form :model="accountForm" :rules="accountRule" ref="accountFormRef" @submit.native="accountFormSubmit" hide-required-asterisk>
            <el-form-item prop="username">
              <el-input type="text" v-model="accountForm.username" placeholder="username" />
            </el-form-item>
            <el-form-item prop="password">
              <el-input type="password" v-model="accountForm.password" placeholder="password" />
            </el-form-item>
            <el-button :disabled="accountBtnDisabled" @click="accountFormSubmit" class="fluid-width" native-type="submit" type="primary">Login</el-button>
          </el-form>
        </el-card>
      </div>
    </div>
  </div>
</template>
<script>
import qs from "querystring";
import { checkIsLogin, saveLoginInfo } from "@/utils/auth";
export default {
  data() {
    return {
      accountForm: {
        username: "lisi",
        password: "abc123",
      },
      accountRule: {
        username: [{ required: true, message: "username is required" }],
        password: [{ required: true, message: "password is required" }],
      },
      accountBtnDisabled: false,
    };
  },
  beforeRouteEnter(to, from, next) {
    if (checkIsLogin()) {
      next(vm => {
        vm.$router.push({ name: "home" });
      });
    } else {
      next();
    }
  },
  methods: {
    accountFormSubmit(e) {
      e.preventDefault();
      this.$refs["accountFormRef"].validate(async valid => {
        if (valid) {
          this.accountBtnDisabled = true;
          // 登录
          const { code, msg, data } = await this.$http.post(
            "/login",
            qs.stringify({
              username: "admin:" + this.accountForm.username,
              password: this.accountForm.password,
            }),
            { headers: { "Content-Type": "application/x-www-form-urlencoded" } },
          );
          if (code === 401 || code === 400) {
            this.$notify({
              title: "Login Fail",
              message: msg,
              type: "error",
              position: "top-right",
              offset: 100,
            });
            this.accountBtnDisabled = false;
          } else {
            saveLoginInfo(data);
            this.$router.push({ name: "home" });
          }
        }
      });
    },
  },
};
</script>

<style lang="scss">
.nw-auth-page {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  background-color: #f0f2f5;
  .auth-container {
    margin-top: -100px;
  }

  .page-login--form {
    width: 310px;
  }

  .form-header {
    font-size: 18px;
    font-weight: bold;
    padding-bottom: 30px;
  }
}
</style>
